package kr.hkit.androidcomplete03.ch22;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {

	ArrayList<Ball> arBall;
	final static int DELAY = 50;
	//final static int RAD = 24;
	
	public MyView(Context context) {
		super(context);
		arBall = new ArrayList<>();
		mHandler.sendEmptyMessageDelayed(0, DELAY);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		for(int i=0; i<arBall.size(); i++){
			arBall.get(i).Draw(canvas);			
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			Ball newBall = Ball.Create((int)event.getX(), (int)event.getY());
			arBall.add(newBall);
			invalidate();
			return true;
		}
		return false;
	}


	Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Ball B;
			
			for(int i=0; i<arBall.size(); i++){
				B = arBall.get(i);
				B.Move(getWidth(), getHeight());
				
				if(B.count>4){
					arBall.remove(i);
					i--;
				}
			}
			invalidate();
			mHandler.sendEmptyMessageDelayed(0, DELAY);
		}
	};

}
